package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.UserDto;
import com.zzyl.entity.User;
import com.zzyl.entity.UserRole;
import com.zzyl.mapper.DeptMapper;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.UserIdMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.UserService;
import com.zzyl.utils.EmptyUtil;
import com.zzyl.utils.NoProcessing;
import com.zzyl.vo.RoleVo;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserIdMapper userIdMapper;

    @Autowired
    private RoleMapper roleMapper;
    //用户分页
    @Override
    public PageResponse<UserVo> userpage(UserDto userDto, Integer pageNum, Integer pageSize) {
//        if (!EmptyUtil.isNullOrEmpty(userDto.getDeptNo())) {
//            userDto.setDeptNo(NoProcessing.processString(userDto.getDeptNo()));
//        }
        if (!EmptyUtil.isNullOrEmpty(userDto.getDeptNo())) {
            //截取部门编号  100001  dept_no like '100001%'
            userDto.setDeptNo(NoProcessing.processString(userDto.getDeptNo()));
        }

        PageHelper.startPage(pageNum, pageSize);

        Page<List<User>> page = userIdMapper.selectPage(userDto);
        PageResponse<UserVo> pageResponse = PageResponse.of(page, UserVo.class);
        if (!EmptyUtil.isNullOrEmpty(pageResponse.getRecords())) {
            List<Long> userIds = pageResponse.getRecords().stream().map(UserVo::getId).collect(Collectors.toList());
            //查询对应角色
            List<RoleVo> roleVoList = roleMapper.findRoleVoListInUserId(userIds);
            //装配数据
            pageResponse.getRecords().forEach(n -> {
                //装配角色
                Set<String> roleVoIds = Sets.newHashSet();
                Set<String> roleVoLabels = Sets.newHashSet();
                roleVoList.forEach(r -> {
                    if (String.valueOf(n.getId()).equals(r.getUserId())) {
                        roleVoIds.add(String.valueOf(r.getId()));
                        roleVoLabels.add(r.getRoleName());
                    }
                });
                n.setRoleLabels(roleVoLabels);
                n.setRoleVoIds(roleVoIds);
            });
        }
        return pageResponse;

    }
    //用户添加
    @Override
    public UserVo add(UserDto userDto) {
       /* if (isLowestDept(userDto.getDeptNo())) {
            throw new BaseException(BasicEnum.USER_LOCATED_BOTTOMED_DEPT);
        }*/

        //转换UserVo为User
        User user = BeanUtil.toBean(userDto, User.class);
        user.setUsername(user.getEmail());
        user.setNickName(user.getRealName());
        user.setDataState(SuperConstant.DATA_STATE_0);
        //TODO 需要设置默认，并且需要加密
        String password = "rxl666";
        user.setPassword(password);

        int flag = userIdMapper.insert(user);
   /*     if (flag == 0) {
            throw new RuntimeException("保存用户信息出错");
        }*/
        //保存用户角色中间表
        List<UserRole> userRoles = Lists.newArrayList();
        userDto.getRoleVoIds().forEach(r -> {
            userRoles.add(UserRole.builder()
                    .userId(user.getId())
                    .roleId(Long.valueOf(r))
                    .dataState(SuperConstant.DATA_STATE_0)
                    .build());
        });
        flag = userRoleMapper.batchInsert(userRoles);
        if (flag == 0) {
            throw new RuntimeException("保存用户角色中间表出错");
        }

        return BeanUtil.toBean(user, UserVo.class);
    }

    @Autowired
    private DeptMapper deptMapper;
    private boolean isLowestDept(String deptNo) {
        int count = deptMapper.isLowestDept(deptNo);
        if (count > 0) {
            return true;
        }
        return false;
    }
    //用户修改

    @Autowired
    private UserRoleMapper userRoleMapper;
    @Override
    public Boolean update(UserDto userDto) {
        //根据部门编号查询，是否是最底层的部门，如果不是，不允许添加用户
       /* if (isLowestDept(userDto.getDeptNo())) {
            throw new BaseException(BasicEnum.USER_LOCATED_BOTTOMED_DEPT);
        }*/
        //转换UserVo为User
        User user = BeanUtil.toBean(userDto, User.class);
        user.setUsername(userDto.getEmail());
        int flag = userIdMapper.update(user);
        if (flag == 0) {
            throw new RuntimeException("修改用户信息出错");
        }


        if (CollUtil.isNotEmpty(userDto.getRoleVoIds())) {
            //删除角色中间表
            userRoleMapper.deleteUserRoleByUserId(user.getId());
//            boolean flagDel = userRoleMapper.deleteUserRoleByUserId(user.getId());
        /*    if (!flagDel) {
                throw new RuntimeException("删除角色中间表出错");
            }*/

            //重新保存角色中间表
            List<UserRole> userRoles = Lists.newArrayList();
            userDto.getRoleVoIds().forEach(r -> {
                userRoles.add(UserRole.builder()
                        .userId(user.getId())
                        .roleId(Long.valueOf(r))
                        .dataState(SuperConstant.DATA_STATE_0)
                        .build());
            });
            flag= userRoleMapper.batchInsert(userRoles);
            if (flag == 0) {
                throw new RuntimeException("保存角色中间表出错");
            }
        }

        return true;
    }

    //启用或禁用用户
    @Override
    public void start(Long id, String status) {
        User user = new User();
        user.setId(id);
        user.setDataState(status);
        userIdMapper.updateStatr(user);
    }

    //用户列表
    @Override
    public List<UserVo> list(UserDto userDto) {
        List<User> list =   userIdMapper.list(userDto);
        List<UserVo> userVoList = BeanUtil.copyToList(list, UserVo.class);
        return userVoList;
    }

    //删除用户
    @Override
    public int delete(String userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteRole(userId);
        // 删除用户与岗位关联
        return userIdMapper.delete(userId);
    }

    @Override
    public void resetPwd(String userId) {
        String newPsd = BCrypt.hashpw("rxl666", BCrypt.gensalt());
        userIdMapper.resetPwd(userId, newPsd);
    }
}
